package com.gxa.token.service.impl;

import com.gxa.token.service.TokenRefreshService;
import com.gxa.token.util.JwtUtil;
import dto.ResultDTO;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import param.AuthParam;
import param.LoginParam;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class TokenRefreshServiceImpl implements TokenRefreshService {

    @Resource(name = "objectRedisTemplate")
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public ResultDTO refreshToken(AuthParam authParam) {
        String token = authParam.getToken();
        Integer userId = JwtUtil.getUserId(token);
        if(redisTemplate.hasKey("token:"+userId)){
            Object o =  redisTemplate.opsForHash().get("token:" + userId, token);
            redisTemplate.delete("token:"+userId);
            System.out.println(o);
            //生成新的token
            String newToken = JwtUtil.sign("新的token", userId);
            redisTemplate.opsForHash().put("token:"+userId,newToken,o);
            LoginParam loginParam = new LoginParam();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:sss");
            String format = simpleDateFormat.format(new Date());
            loginParam.setCreateTime(format);
            loginParam.setIndate("3");
            loginParam.setToken(newToken);
            return new ResultDTO(200,"success",loginParam);
        }
        return new ResultDTO(1001,"token失效请重新登录");
    }
}
